import {Component, OnInit, ViewChild} from '@angular/core';
import {BasePage} from '../../common/basePage';
import {NavController, ToastController} from '@ionic/angular';
import {HttpService} from '../../services/http.service';
import {UrlAndOPT} from '../../common/url-and-opt.enum';
import {Observable} from 'rxjs';

/**
 * 我的出借
 */
@Component({
  selector: 'app-user-lend',
  templateUrl: './user-lend.page.html',
  styleUrls: ['./user-lend.page.scss'],
})
export class UserLendPage extends BasePage implements OnInit {

  @ViewChild('infiniteScroll') infiniteScroll;
  public dataList: any[] = [];
  // 筛选条件
  public condition: any = {
    currPage: 1, // 当前页码
    pageSize: 20 // 每页数据条数
  };

  constructor(
    public navCtrl: NavController,
    public toastCtrl: ToastController,
    private service$: HttpService
  ) {
    super(navCtrl, toastCtrl);
  }

  ngOnInit() {
    this.getDataList()
      .subscribe(obj => {
        this.handler(obj);
      });
  }

  // 获取列表数据
  private getDataList(): Observable<any> {
    return this.service$.doRequest(UrlAndOPT.auth_user_lend, this.condition);
  }

  private handler(obj) {
    if (obj) {
      const records = obj.records;
      this.condition = {...this.condition, currPage: records['currPage'], pageSize: records['pageSize']};
      this.dataList = records['page'];
      // 根据列表长度判断是否禁用加载
      this.infiniteScroll.disabled = this.dataList.length === records['totalCount'];
    } else {
      this.infiniteScroll.disabled = true;
    }
  }

  // 下拉刷新列表
  doRefresh(event) {
    this.condition.currPage = 1;
    this.getDataList()
      .subscribe(obj => {
        this.handler(obj);
        event.target.complete();
      });
  }

  // 上拉加载更多
  loadMoreData(event) {
    this.condition.currPage++;
    this.getDataList()
      .subscribe(obj => {
        if (obj) {
          const records = obj.records;
          // 累加数据
          this.dataList = [...this.dataList, ...records['page']];
          // 根据列表长度判断是否禁用加载
          this.infiniteScroll.disabled = this.dataList.length === records['totalCount'];
        }
        // 关闭上拉组件
        event.target.complete();
      });
  }

  pushDetail(data) {
    this.navCtrl.navigateForward(['/auth/user-lend-detail', {data: JSON.stringify(data)}]);
  }

}
